package mymgo

import (
	"errors"

	"lottery/conf"
	"sync"
)

var mux sync.RWMutex
var cacheSess map[string]*MdbSession

func init() {
	cacheSess = make(map[string]*MdbSession)
}

func Open(name string) (sess *MdbSession, err error) {
	var ok bool
	mux.RLock()
	sess, ok = cacheSess[name]
	mux.RUnlock()

	if ok {
		return
	}

	res := conf.LoadResource()

	mgoCfg, ok := res.Mongo[name]
	if !ok {
		err = errors.New("配置不存在")
		return
	}

	sess = GetDb(mgoCfg)

	mux.Lock()
	cacheSess[name] = sess
	mux.Unlock()
	return
}

func OpenBase() (db *MdbSession, err error) {
	return Open("base")
}
